const socket = require('socket.io')
const http = require('http')

const server = http.createServer()

const io = socket(server, {
  cors: {
    origin: '*',
  },
})

io.on('connection', (sock) => {
  console.log('连接成功')
  // 向客户端发送连接成功的消息
  sock.emit('connectionSuccess')

  // 监听加入房间的事件
  sock.on('joinRoom', (roomId) => {
    sock.join(roomId)
  })

  // 在房间里广播callRemote事件
  sock.on('callRemote', (roomId) => {
    io.to(roomId).emit('callRemote')
  })

  // 在房间里广播acceptCall事件
  sock.on('acceptCall', (roomId) => {
    io.to(roomId).emit('acceptCall')
  })

  // 接收offer
  sock.on('sendOffer', ({ offer, roomId }) => {
    io.to(roomId).emit('sendOffer', offer)
  })

  // 接收answer
  sock.on('sendAnswer', ({ answer, roomId }) => {
    io.to(roomId).emit('sendAnswer', answer)
  })

  // 接收candidate
  sock.on('sendCandidate', ({ candidate, roomId }) => {
    io.to(roomId).emit('sendCandidate', candidate)
  })
})

server.listen(3000, () => {
  console.log('服务器启动成功')
})
